
import 'package:t3_data_service/biz_data_source/map/poi/map_poi.dart';
import 'package:t3_foundation/t3_foundation.dart';

typedef POISearchChannelMsgChannel = Future<Map?> Function(Map<String, dynamic>?);

class POISearchChannel {

  static POISearchChannelMsgChannel? _channel;

  static registerChannel(POISearchChannelMsgChannel channel) {
    _channel = channel;
  }

  static Future<Map?> sendMsgToChannel(String action, {Map<String, dynamic>? msgData}) {
    if (_channel != null) {
      Map<String, dynamic> map = {
        'action':action,
      };
      if (msgData != null) {
        map['data'] = msgData;
      }
      return _channel!(map);
    }
    return Future.value(null);
  }

  /// 逆地理成外部POI
  static Future<AddressPoi?> regeoPoint(LatLng location) async {
    if (!LatLng.isLatLngValid(location)) {
      return Future.value(null);
    }
    var result = await sendMsgToChannel('regeo', msgData: {
      'lat':location.lat,
      'lng':location.lng
    });
    // 把Map<dynamic, dynamic> 转化为 Map<String, dynamic>
    // 创建一个新的 Map<String, dynamic>
    Map<String, dynamic> stringKeyMap = {};
    if(result != null && result is Map<dynamic, dynamic>) {
      // 遍历原始 Map 并只添加字符串键的键值对
      for (var entry in result.entries) {
        if (entry.key is String) {
          stringKeyMap[entry.key as String] = entry.value;
        } else {
          // 可选：处理或记录非字符串键
          print('Non-string key found and ignored: ${entry.key}');
        }
      }
    }
    if (stringKeyMap != null && stringKeyMap.isNotEmpty) {
      var poi = AddressPoi.fromJson(stringKeyMap);
      return Future.value(poi);
    }
    return Future.value(null);
  }
  
  static Future<Tuple2<String?, String?>> patchCondition(LatLng? coordinate) async {
    if (LatLng.isLatLngValid(coordinate)) {
      var result = await sendMsgToChannel('regeo', msgData: {
        'lat':coordinate?.lat ?? 0,
        'lng':coordinate?.lng ?? 0
      });
      if (result != null) {
        var adCode = StringUtils.dynamicToString(result['adCode']);
        var city = StringUtils.dynamicToString(result['city']);
        return Tuple2(adCode, city);
      }
    }
    return const Tuple2(null, null);
  }
}
